package cn.kattomy.shop.user.service.impl;


import java.util.List;

import cn.kattomy.shop.user.dao.UserDao;
import cn.kattomy.shop.user.service.UserService;
import cn.kattomy.shop.user.vo.User;
import cn.kattomy.shop.utils.MD5Utils;
import cn.kattomy.shop.utils.MailUtils;
import cn.kattomy.shop.utils.UUIDUtils;

public class UserServiceImpl implements UserService {

	private UserDao userDao;
	
	public void setUserDao(UserDao userdao) {
		this.userDao = userdao;
	}

	@Override
	public boolean validateUsername(String username) {
		User user = userDao.queryUserByUsername(username);
		return  user != null;
	}

	@Override
	public String test() {
		return "Testing";
	}

	@Override
	public void save(User user) {
		user.setState(0);//0代表用户未激活,1代表用户已激活
		String password = MD5Utils.getMD5(user.getPassword());
		user.setPassword(password);
		String  code = UUIDUtils.getUUID();
		user.setCode(code);
		userDao.saveOrUpdate(user);
		MailUtils.sendMail(user.getEmail(), code);
	}



	@Override
	public boolean activateUser(String code) {
		User user = userDao.queryUserByCode(code);
		if (user == null) {
			return false;
		}
		user.setCode(null);
		user.setState(1);
		userDao.saveOrUpdate(user);
		return true;
	}

	@Override
	public User login(User user) {
		String password = MD5Utils.getMD5(user.getPassword());
		user.setPassword(password);
		User existUser =  userDao.queryUserByMultiCondition(user);
		if(existUser == null){
			existUser = userDao.queryUserByMultiCondition2(user);
		}
		return existUser;
	}

	@Override
	public List<User> findAll() {
		return userDao.findAll();
	}

	@Override
	public boolean validateEmail(String email) {
		User user = userDao.queryUserByEmail(email);
		return  user != null;
	}

	

}
